介紹如何寫程式來播放音樂檔於Windows Mobile使用
更多文章,請到我在點部落所建立的部落格「.NET菜鳥自救會」閱讀
http://www.dotblogs.com.tw/chou/
播放 wav 音效檔
透過 Windows API 中,Coredll.dll 內的 PlaySound 可以播放一些音效檔。
宣告方式
    [DllImport("CoreDll.DLL", EntryPoint="PlaySound", SetLastError=true)]
    private extern static int PlaySound(string szSound, IntPtr hMod, int flags);
將以下播放音效的程式碼,整合到上一篇文章 音量控制 中,可以撥音效與調整音量大小。
程式碼
        [DllImport("CoreDll.DLL", EntryPoint="PlaySound", SetLastError=true)]
        private extern static int PlaySound(string szSound, IntPtr hMod, int flags);
        public const int SND_FILENAME = 0x00020000; // file name
        public const int SND_SYNC = 0x0000;  // play synchronously (default)
        private void button1_Click(object sender, EventArgs e)
        {
            PlaySound("\\windows\\Alarm2.wav", IntPtr.Zero, 0);
        }
執行結果

先將 WMPLib 加入參考,檔名為 C:\WINDOWS\system32\wmp.dll


以下程式碼功能為將 \Storage Card\Music 的檔案顯示於 ListBox 中,使用者可撥放與停止播放 mp3 音樂檔。
程式碼
        WMPLib.WindowsMediaPlayer Player;
        private void Form4_Load(object sender, EventArgs e)
        {
            foreach (string s in System.IO.Directory.GetFiles(@"\Storage Card\Music") )
            {
                this.listBox1.Items.Add(s);
            }
            Player = new WMPLib.WindowsMediaPlayer(); 
            Player.settings.volume = 10;
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            // Play music file
            if (this.listBox1.SelectedIndex >= 0)
            {
                Player.URL = this.listBox1.SelectedItem.ToString();
                Player.controls.play();
            }
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            // Stop music file
            Player.controls.stop();
        }
執行結果
